package com.alex.httphack;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpMessage;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.HeaderGroup;

import com.alex.common.ILogger;

public class HeaderFactory implements ILogger {

	private static final HeaderGroup defaultHeaderGroup = newHeaderGroup();

	public static HeaderGroup newHeaderGroup() {
		HeaderGroup heads = new HeaderGroup();
		heads.addHeader(new BasicHeader(HttpHeaders.ACCEPT,
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
		heads.addHeader(new BasicHeader(HttpHeaders.ACCEPT_CHARSET,
				"GBK,utf-8;q=0.7,*;q=0.3"));
		heads.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING,
				"gzip,deflate,sdch"));
		// ("Connection", "keep-alive");
		heads.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE,
				"zh-CN,zh;q=0.8"));
		heads.addHeader(new BasicHeader(HttpHeaders.CACHE_CONTROL, "max-age=0"));
		heads.addHeader(new BasicHeader(
				HttpHeaders.USER_AGENT,
				"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13"));
		heads.addHeader(new BasicHeader(HttpHeaders.REFERER,
				"http://www.china.com/"));
		return heads;
	}

	public static HeaderGroup newHeaderGroup(String[] headers) {
		HeaderGroup group = newHeaderGroup();
		if (headers != null && headers.length > 0) {
			for (String header : headers) {
				if (header != null && header.length() > 2
						&& header.indexOf(':') > 0) {
					int split = header.indexOf(':');
					Header hd = new BasicHeader(header.substring(0, split)
							.trim(), header.substring(split + 1).trim());
					group.updateHeader(hd);
				}
			}
		}
		return group;
	}

	public static void setHeaderGroup(HttpMessage httpMessage,
			HeaderGroup headerGroup) {
		if (headerGroup != null) {
			httpMessage.setHeaders(headerGroup.getAllHeaders());
		}
	}

	public static void copyHeaders(HttpServletResponse response,
			Header[] headers) {
		if (response != null && headers != null && headers.length > 0) {
			for (Header header : headers) {
				response.setHeader(header.getName(), header.getValue());
			}
		}
	}

	public static String formatHeaders(Header[] headers) {
		if (headers != null && headers.length > 0) {
			StringBuilder sb = new StringBuilder();
			for (Header header : headers) {
				sb.append(header.toString()).append(RN);
			}
			return sb.toString();
		}
		return "";
	}

	public static void setHeaderGroup(HttpMessage httpMessage) {
		httpMessage.setHeaders(defaultHeaderGroup.getAllHeaders());
	}

	public static void main(String[] args) {
		System.out.println(newHeaderGroup(new String[] { "rrr:ttt", ":", "fff",
				"  :  " }));
	}
}
